﻿@model List<Model.NumberingRule>
@{
    ViewData["Title"] = "编号规则管理";
}
<!-- 防伪令牌 -->
@Html.AntiForgeryToken()
<!-- 引入依赖 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js?v=1.0"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css?v=1.0" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js?v=1.0"></script>

<style>
    /* === 全局样式 === */
    body {
        overflow: hidden;
        font-family: "Microsoft YaHei", sans-serif;
    }

    /* === 导航栏样式 === */
    .navbar {
        height: 56px;
        background-color: #fff;
        border-bottom: 1px solid #eee;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .nav-items {
        display: flex;
        gap: 10px;
    }

    .nav-item {
        padding: 0 15px;
        height: 56px;
        line-height: 56px;
        cursor: pointer;
        position: relative;
        text-decoration: none;
        color: #333;
        font-size: 14px;
    }

        .nav-item.active {
            background-color: #f5f5f5;
            border-bottom: 2px solid #28a745;
        }

        .nav-item:hover {
            background-color: #f9f9f9;
        }

    /* === 其他操作下拉菜单 === */
    .other-operations {
        position: relative;
    }

    .operations-btn {
        background: none;
        border: none;
        padding: 8px 15px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 5px;
        font-size: 14px;
    }

    .operations-menu {
        position: absolute;
        top: 40px;
        right: 0;
        width: 150px;
        background-color: white;
        border: 1px solid #eee;
        border-radius: 4px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 5px 0;
        z-index: 300;
        display: none;
    }

        .operations-menu.show {
            display: block;
        }

    .operation-item {
        padding: 8px 15px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
    }

        .operation-item:hover {
            background-color: #f5f5f5;
        }

    /* === 页面布局 === */
    .page-container {
        display: flex;
        width: 100%;
        height: calc(100vh - 56px);
    }

    /* === 左侧列表区域 === */
    .list-area {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
    }

    /* === 遮罩层 === */
    .mask {
        position: fixed;
        top: 56px;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 100;
        display: none;
        cursor: pointer;
    }

    /* === Edit视图弹窗容器（备用） === */
    .edit-modal-container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 200;
        width: 450px;
        background-color: white;
        box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
        border-radius: 4px;
        overflow-y: auto;
        display: none;
    }

    /* === 搜索栏样式 === */
    .search-bar {
        background: white;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 20px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .search-row {
        display: flex;
        align-items: flex-end;
        gap: 15px;
        flex-wrap: wrap;
    }

    .search-item {
        display: flex;
        flex-direction: column;
        position: relative;
    }

    .search-label {
        font-size: 12px;
        margin-bottom: 5px;
        color: #666;
        white-space: nowrap;
    }

    .search-control {
        width: 150px;
        height: 32px;
        padding: 5px 10px;
        font-size: 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        transition: all 0.2s;
    }

        .search-control:hover {
            border-color: #28a745;
        }

        .search-control:focus {
            outline: none;
            border-color: #28a745;
            box-shadow: 0 0 0 2px rgba(40, 167, 69, 0.1);
        }

    /* === 自定义下拉框样式 === */
    .custom-select {
        position: relative;
        width: 150px;
    }

    .select-display {
        width: 100%;
        height: 32px;
        padding: 5px 10px;
        font-size: 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        background-color: white;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: space-between;
        transition: all 0.2s;
    }

        .select-display:hover {
            border-color: #28a745;
        }

        .select-display::after {
            content: "▼";
            font-size: 10px;
            color: #666;
            transition: transform 0.2s;
        }

        .select-display.active::after {
            transform: rotate(180deg);
        }

    .select-options {
        position: absolute;
        top: 100%;
        left: 0;
        width: 100%;
        max-height: 200px;
        overflow-y: auto;
        background-color: white;
        border: 1px solid #ddd;
        border-top: none;
        border-radius: 0 0 4px 4px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        z-index: 10;
        display: none;
    }

        .select-options.show {
            display: block;
        }

    .select-option {
        padding: 8px 10px;
        font-size: 12px;
        cursor: pointer;
        transition: background-color 0.2s;
    }

        .select-option:hover {
            background-color: #f0f7ee;
            color: #28a745;
        }

        .select-option.selected {
            background-color: #e6f4ea;
            color: #28a745;
            font-weight: 500;
        }

    /* 自定义下拉框滚动条样式 */
    .select-options::-webkit-scrollbar {
        width: 6px;
    }

    .select-options::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }

    .select-options::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 3px;
    }

        .select-options::-webkit-scrollbar-thumb:hover {
            background: #aaa;
        }

    /* === 双日历选择器样式 === */
    .custom-date-range {
        position: relative;
        width: 150px;
    }

    .date-range-popup {
        position: absolute;
        top: 100%;
        left: 0;
        background-color: white;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        padding: 15px;
        z-index: 100;
        display: none;
        gap: 20px;
        width: 600px;
    }

        .date-range-popup.show {
            display: flex;
        }

    .date-calendar {
        flex: 1;
        vertical-align: top;
    }

    .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        padding: 0 5px;
    }

    .month-nav {
        background: none;
        border: none;
        cursor: pointer;
        color: #666;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        font-size: 12px;
    }

        .month-nav:hover {
            background-color: #f0f7ee;
            color: #28a745;
        }

    .current-month {
        font-weight: 600;
        font-size: 13px;
    }

    .weekdays {
        display: flex;
        margin-bottom: 5px;
    }

    .weekday {
        flex: 1;
        text-align: center;
        font-size: 12px;
        color: #666;
        padding: 5px 0;
    }

    .calendar-days {
        display: flex;
        flex-wrap: wrap;
    }

    .calendar-day {
        width: 14.28%;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        cursor: pointer;
        border-radius: 4px;
        margin-bottom: 2px;
    }

        .calendar-day:hover {
            background-color: #f0f7ee;
        }

        .calendar-day.other-month {
            color: #ccc;
        }

        .calendar-day.selected {
            background-color: #28a745;
            color: white;
        }

        .calendar-day.in-range {
            background-color: #e6f4ea;
        }

    .calendar-actions {
        margin-top: 15px;
        text-align: right;
        padding-top: 10px;
        border-top: 1px solid #eee;
        margin-top: auto;
    }

    /* === 按钮样式 === */
    .search-button {
        height: 32px;
        padding: 5px 15px;
        font-size: 12px;
        border: 1px solid;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
    }

    .btn-reset {
        color: #6c757d;
        background-color: transparent;
        border-color: #6c757d;
    }

        .btn-reset:hover {
            color: #fff;
            background-color: #28a745;
            border-color: #28a745;
        }

    .btn-query {
        color: #fff;
        background-color: #28a745;
        border-color: #28a745;
    }

        .btn-query:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }

    .btn-export {
        color: #6c757d;
        background-color: transparent;
        border-color: #6c757d;
        margin-top: 10px;
    }

        .btn-export:hover {
            color: #fff;
            background-color: #28a745;
            border-color: #28a745;
        }

    /* === 表格样式 === */
    .table {
        width: 100%;
        border-collapse: collapse;
        font-size: 12px;
    }

        .table th, .table td {
            white-space: nowrap;
            padding: 8px 12px;
            border: 1px solid #dee2e6;
        }

        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }

            /* 复选框样式 */
            .table th input[type="checkbox"],
            .table td input[type="checkbox"] {
                cursor: pointer;
                width: 16px;
                height: 16px;
                accent-color: #28a745;
            }

    /* 编辑按钮样式 */
    .edit-btn {
        color: #28a745;
        text-decoration: none;
        cursor: pointer;
    }

        .edit-btn:hover {
            color: #218838;
            text-decoration: underline;
        }

    /* === 响应式调整 === */
    @@media (max-width: 1200px) {
        .search-row {
            flex-wrap: wrap;
            gap: 15px;
        }
    }

    /* 右侧编辑面板 */
    .edit-panel {
        position: fixed;
        top: 56px;
        right: 0;
        bottom: 0;
        width: 450px;
        background-color: #fff;
        box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
        border-radius: 4px 0 0 4px;
        overflow-y: auto;
        z-index: 100;
        display: none;
    }
</style>

<!-- 遮罩层 -->
<div class="mask" id="mask"></div>

<!-- Edit视图弹窗容器（备用） -->
<div class="edit-modal-container" id="editModalContainer"></div>

<!-- 页面内容 -->
<div class="page-container">
    <!-- 左侧列表区域 -->
    <div class="list-area" id="listArea">
        <!-- 搜索栏 -->
        <div class="search-bar">
            <div class="search-row">
                <!-- 目标表单 -->
                <div class="search-item">
                    <label class="search-label">目标表单</label>
                    <div class="custom-select" id="targetFormSelect">
                        <div class="select-display" id="targetFormDisplay">请选择</div>
                        <div class="select-options" id="targetFormOptions">
                            <div class="select-option" data-value="货品信息">货品信息</div>
                            <div class="select-option" data-value="入库单">入库单</div>
                            <div class="select-option" data-value="出库单">出库单</div>
                            <div class="select-option" data-value="盘点单">盘点单</div>
                            <div class="select-option" data-value="调拨单">调拨单</div>
                            <div class="select-option" data-value="进货单">进货单</div>
                            <div class="select-option" data-value="进货退货单">进货退货单</div>
                            <div class="select-option" data-value="销售单">销售单</div>
                            <div class="select-option" data-value="销售退货单">销售退货单</div>
                            <div class="select-option" data-value="领用订单">领用订单</div>
                            <div class="select-option" data-value="客户">客户</div>
                            <div class="select-option" data-value="供应商">供应商</div>
                        </div>
                    </div>
                </div>

                <!-- 编号前缀 -->
                <div class="search-item">
                    <label class="search-label">编号前缀</label>
                    <input type="text" class="search-control" id="searchNumberPrefix" placeholder="请输入编号前缀">
                </div>

                <!-- 时间规则 -->
                <div class="search-item">
                    <label class="search-label">时间规则</label>
                    <input type="text" class="search-control" id="searchTimeRule" placeholder="请输入时间规则">
                </div>

                <!-- 操作时间 - 双日历选择器 -->
                <div class="search-item">
                    <label class="search-label">操作时间</label>
                    <div class="custom-date-range" id="dateRangePicker">
                        <div class="select-display" id="dateRangeDisplay">请选择</div>
                        <div class="date-range-popup" id="dateRangePopup">
                            <!-- 开始日期日历 -->
                            <div class="date-calendar">
                                <div class="calendar-header">
                                    <button class="month-nav prev" data-calendar="start">&lt;&lt;</button>
                                    <button class="month-nav prev-month" data-calendar="start">&lt;</button>
                                    <span class="current-month" data-calendar="start">2025-10</span>
                                    <button class="month-nav next-month" data-calendar="start">&gt;</button>
                                    <button class="month-nav next" data-calendar="start">&gt;&gt;</button>
                                </div>
                                <div class="weekdays">
                                    <div class="weekday">日</div>
                                    <div class="weekday">一</div>
                                    <div class="weekday">二</div>
                                    <div class="weekday">三</div>
                                    <div class="weekday">四</div>
                                    <div class="weekday">五</div>
                                    <div class="weekday">六</div>
                                </div>
                                <div class="calendar-days" id="startCalendarDays">
                                    <!-- 日期通过JS生成 -->
                                </div>
                            </div>

                            <!-- 结束日期日历 -->
                            <div class="date-calendar">
                                <div class="calendar-header">
                                    <button class="month-nav prev" data-calendar="end">&lt;&lt;</button>
                                    <button class="month-nav prev-month" data-calendar="end">&lt;</button>
                                    <span class="current-month" data-calendar="end">2025-10</span>
                                    <button class="month-nav next-month" data-calendar="end">&gt;</button>
                                    <button class="month-nav next" data-calendar="end">&gt;&gt;</button>
                                </div>
                                <div class="weekdays">
                                    <div class="weekday">日</div>
                                    <div class="weekday">一</div>
                                    <div class="weekday">二</div>
                                    <div class="weekday">三</div>
                                    <div class="weekday">四</div>
                                    <div class="weekday">五</div>
                                    <div class="weekday">六</div>
                                </div>
                                <div class="calendar-days" id="endCalendarDays">
                                    <!-- 日期通过JS生成 -->
                                </div>
                            </div>

                            <!-- 日历按钮区域 -->
                            <div class="calendar-actions">
                                <button class="search-button btn-reset" id="clearDateBtn">清除</button>
                                <button class="search-button btn-query" id="confirmDateBtn">确定</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 重置按钮 -->
                <div class="search-item">
                    <label class="search-label" style="visibility: hidden;">重置</label>
                    <button class="search-button btn-reset" id="resetSearch">重置</button>
                </div>

                <!-- 查询按钮 -->
                <div class="search-item">
                    <label class="search-label" style="visibility: hidden;">查询</label>
                    <button class="search-button btn-query" id="doSearch">查询</button>
                </div>
            </div>
            <!-- 新增按钮 -->
            <button class="search-button btn-query" id="addNew">新增</button> 
            <!-- 导出按钮 -->
            <button class="search-button btn-export" id="exportData">导出</button>
        </div>

        <!-- 数据表格 -->
        <table class="table table-hover">
            <thead class="table-light">
                <tr>
                    <th><input type="checkbox" class="form-check-input" id="selectAll"></th>
                    <th>序号</th>
                    <th>目标表单</th>
                    <th>编号前缀</th>
                    <th>时间规则</th>
                    <th>流水号位数</th>
                    <th>步长</th>
                    <th>编号生成规则</th>
                    <th>当前最大值</th>
                    <th>最后更新时间</th>
                    <th>创建人</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="ruleTableBody">
                @if (Model != null && Model.Count > 0)
                {
                    for (int i = 0; i < Model.Count; i++)
                    {
                        var item = Model[i];
                        <tr>
                            <td><input type="checkbox" class="form-check-input row-checkbox" data-id="@item.RuleId"></td>
                            <td>@(i + 1)</td>
                            <td>@item.TargetForm</td>
                            <td>@item.NumberPrefix</td>
                            <td>@item.TimeRule</td>
                            <td>@item.SerialNumberDigit</td>
                            <td>@item.Step</td>
                            <td>@item.NumberGenerationRule</td>
                            <td>@item.MaxValue</td>
                            <td>@item.LastUpdateTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
                            <td>@item.CreateBy</td>
                            <td>@item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
                            <td>
                                <a href="javascript:;" class="edit-btn" data-id="@item.RuleId">编辑</a>
                                <a href="javascript:;" class="delete-btn" data-id="@item.RuleId" style="margin-left: 5px; color: #28a745; text-decoration: none; cursor: pointer;">删除</a>
                            </td>
                        </tr>
                    }
                }
                else
                {
                    <tr>
                        <td colspan="13" style="text-align: center;">暂无数据</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>

    <!-- 右侧编辑面板 -->
    <div class="edit-panel" id="editPanel"></div>
</div>

<script>
    $(document).ready(function () {
        // 初始化变量
        const $targetFormDisplay = $("#targetFormDisplay");
        const $targetFormOptions = $("#targetFormOptions");
        const $editPanel = $("#editPanel");
        const $dateRangeDisplay = $("#dateRangeDisplay");
        const $dateRangePopup = $("#dateRangePopup");
        let selectedDates = { start: null, end: null }; // 双日历选中的日期

        // 1. 自定义下拉框逻辑（目标表单）
        $targetFormDisplay.click(function (e) {
            e.stopPropagation();
            $targetFormOptions.toggleClass("show");
            $targetFormDisplay.toggleClass("active");
        });

        $(".select-option").click(function () {
            const value = $(this).data("value");
            $targetFormDisplay.text(value);
            $(".select-option").removeClass("selected");
            $(this).addClass("selected");
            $targetFormOptions.removeClass("show");
            $targetFormDisplay.removeClass("active");
        });

        $(document).click(function () {
            $targetFormOptions.removeClass("show");
            $targetFormDisplay.removeClass("active");
        });

        // 2. 双日历选择器完整逻辑
        (function () {
            const $startCalendarDays = $("#startCalendarDays");
            const $endCalendarDays = $("#endCalendarDays");
            const $confirmDateBtn = $("#confirmDateBtn");
            const $clearDateBtn = $("#clearDateBtn");
            let currentMonths = { start: new Date(), end: new Date() };

            // 初始化日历
            initCalendars();

            // 点击显示/隐藏日历
            $dateRangeDisplay.click(function (e) {
                e.stopPropagation();
                $(this).toggleClass("active");
                $dateRangePopup.toggleClass("show");
            });

            // 点击页面其他区域关闭日历
            $(document).click(function (e) {
                if (!$(e.target).closest(".custom-date-range").length) {
                    $dateRangeDisplay.removeClass("active");
                    $dateRangePopup.removeClass("show");
                }
            });

            // 月份导航按钮
            $(".month-nav").click(function (e) {
                e.stopPropagation();
                const calendarType = $(this).data("calendar");
                const action = $(this).hasClass("prev") ? "year-prev" :
                              $(this).hasClass("next") ? "year-next" :
                              $(this).hasClass("prev-month") ? "month-prev" : "month-next";
                navigateMonth(calendarType, action);
            });

            // 确定日期选择
            $confirmDateBtn.click(function () {
                if (selectedDates.start && selectedDates.end) {
                    const startStr = formatDate(selectedDates.start);
                    const endStr = formatDate(selectedDates.end);
                    $dateRangeDisplay.text(`${startStr} - ${endStr}`);
                } else if (selectedDates.start) {
                    $dateRangeDisplay.text(formatDate(selectedDates.start));
                }
                $dateRangeDisplay.removeClass("active");
                $dateRangePopup.removeClass("show");
            });

            // 清除日期选择
            $clearDateBtn.click(function () {
                selectedDates.start = null;
                selectedDates.end = null;
                $dateRangeDisplay.text("请选择");
                renderCalendars();
            });

            // 初始化日历
            function initCalendars() {
                updateMonthDisplay("start");
                updateMonthDisplay("end");
                renderCalendars();
            }

            // 渲染两个日历
            function renderCalendars() {
                renderSingleCalendar("start", currentMonths.start, $startCalendarDays);
                renderSingleCalendar("end", currentMonths.end, $endCalendarDays);
            }

            // 渲染单个日历
            function renderSingleCalendar(type, date, container) {
                container.empty();
                const year = date.getFullYear();
                const month = date.getMonth();
                const firstDay = new Date(year, month, 1);
                const lastDay = new Date(year, month + 1, 0);
                const firstDayOfWeek = firstDay.getDay();
                const prevMonthLastDay = new Date(year, month, 0).getDate();

                // 上月残留日期
                for (let i = 0; i < firstDayOfWeek; i++) {
                    const day = prevMonthLastDay - firstDayOfWeek + i + 1;
                    container.append(createDayElement(day, true, type));
                }

                // 当月日期
                for (let i = 1; i <= lastDay.getDate(); i++) {
                    const dayEl = createDayElement(i, false, type);
                    const currentDate = new Date(year, month, i);
                    if (selectedDates[type] && currentDate.toDateString() === selectedDates[type].toDateString()) {
                        dayEl.addClass("selected");
                    }
                    if (selectedDates.start && selectedDates.end) {
                        const isInRange = currentDate >= selectedDates.start && currentDate <= selectedDates.end;
                        const isSelected = currentDate.toDateString() === selectedDates.start.toDateString() ||
                                          currentDate.toDateString() === selectedDates.end.toDateString();
                        if (isInRange && !isSelected) dayEl.addClass("in-range");
                    }
                    container.append(dayEl);
                }

                // 下月补充日期
                const totalDays = firstDayOfWeek + lastDay.getDate();
                const nextMonthNeedDays = 42 - totalDays;
                for (let i = 1; i <= nextMonthNeedDays; i++) {
                    container.append(createDayElement(i, true, type));
                }
            }

            // 创建日期元素
            function createDayElement(day, isOtherMonth, type) {
                const dayEl = $("<div>").addClass("calendar-day");
                if (isOtherMonth) dayEl.addClass("other-month");
                dayEl.text(day);
                dayEl.click(function (e) {
                    e.stopPropagation();
                    selectDate(type, day, isOtherMonth);
                });
                return dayEl;
            }

            // 选中日期
            function selectDate(type, day, isOtherMonth) {
                let date = new Date(currentMonths[type]);
                if (isOtherMonth) {
                    date.setMonth(day < 15 ? date.getMonth() + 1 : date.getMonth() - 1);
                }
                date.setDate(day);

                if (type === "start") {
                    if (selectedDates.end && date > selectedDates.end) selectedDates.end = null;
                    selectedDates.start = date;
                } else {
                    selectedDates.end = date;
                }
                renderCalendars();
            }

            // 月份导航
            function navigateMonth(type, action) {
                const date = currentMonths[type];
                switch (action) {
                    case "year-prev": date.setFullYear(date.getFullYear() - 1); break;
                    case "year-next": date.setFullYear(date.getFullYear() + 1); break;
                    case "month-prev": date.setMonth(date.getMonth() - 1); break;
                    case "month-next": date.setMonth(date.getMonth() + 1); break;
                }
                updateMonthDisplay(type);
                renderSingleCalendar(type, date, type === "start" ? $startCalendarDays : $endCalendarDays);
            }

            // 更新月份显示
            function updateMonthDisplay(type) {
                const date = currentMonths[type];
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                $(`.current-month[data-calendar="${type}"]`).text(`${year}-${month}`);
            }

            // 格式化日期
            function formatDate(date) {
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                return `${year}-${month}-${day}`;
            }
        })();

        // 3. 全选/取消全选逻辑
        $(document).on("change", "#selectAll", function () {
            const isChecked = $(this).prop("checked");
            $(".row-checkbox").prop("checked", isChecked);
        });

        $(document).on("change", ".row-checkbox", function () {
            const allCheckboxes = $(".row-checkbox");
            const checkedCheckboxes = allCheckboxes.filter(":checked");
            $("#selectAll").prop("checked", checkedCheckboxes.length === allCheckboxes.length);
        });

        // 4. 编辑按钮逻辑
        $(document).on("click", ".edit-btn", function () {
            const ruleId = $(this).data("id");
            $editPanel.show().html("<div style='padding:20px;text-align:center;'>加载中...</div>");

            $.ajax({
                url: `/NumberingRules/Edit?id=${ruleId}`,
                type: "GET",
                success: function (response) {
                    $editPanel.html(response);
                },
                error: function (xhr) {
                    alert("加载编辑视图失败，状态码：" + xhr.status);
                    $editPanel.hide();
                }
            });
        });

        // 5. 关闭编辑面板
        $(document).on("click", ".close-modal-btn", function () {
            $editPanel.hide();
        });

        // 6. 刷新表格函数
        window.refreshRuleTable = function () {
            const targetForm = $targetFormDisplay.text() === "请选择" ? "" : $targetFormDisplay.text();
            const numberPrefix = $("#searchNumberPrefix").val().trim();
            const timeRule = $("#searchTimeRule").val().trim();
            const operateTime = $dateRangeDisplay.text() === "请选择" ? "" : $dateRangeDisplay.text();

            // 显示加载状态
            $("#ruleTableBody").html('<tr><td colspan="13" style="text-align:center;">查询中...</td></tr>');

            $.ajax({
                url: "/NumberingRules/Index",
                type: "GET",
                data: {
                    targetForm: targetForm,
                    numberPrefix: numberPrefix,
                    timeRule: timeRule,
                    operateTime: operateTime
                },
                success: function (html) {
                    const $newTableBody = $(html).find("#ruleTableBody");
                    $("#ruleTableBody").replaceWith($newTableBody);
                },
                error: function (xhr) {
                    $("#ruleTableBody").html(`<tr><td colspan="13" style="text-align:center;color:red;">刷新失败：${xhr.statusText}</td></tr>`);
                    alert("刷新列表失败，请稍后重试");
                }
            });
        };

        // 7. 新增按钮
        $("#addNew").click(function () {
            $editPanel.show().html("<div style='padding:20px;text-align:center;'>加载中...</div>");
            $.ajax({
                url: "/NumberingRules/Add",
                type: "GET",
                success: function (data) {
                    $editPanel.html(data);
                }
            });
        });

        // 8. 查询按钮（核心修复：异步请求+局部更新）
        $("#doSearch").click(function () {
            window.refreshRuleTable(); // 直接调用刷新表格函数
        });

        // 9. 重置按钮
        $("#resetSearch").click(function () {
            $targetFormDisplay.text("请选择");
            $("#searchNumberPrefix").val("");
            $("#searchTimeRule").val("");
            $("#dateRangeDisplay").text("请选择");
            selectedDates = { start: null, end: null };
            refreshRuleTable("");
        });
        // 10. 导出按钮
        $("#exportData").click(function () {
            const selectedIds = [];
            $(".row-checkbox:checked").each(function () {
                selectedIds.push($(this).data("id"));
            });

            const targetForm = $targetFormDisplay.text() === "请选择" ? "" : $targetFormDisplay.text();
            const numberPrefix = $("#searchNumberPrefix").val().trim();
            const timeRule = $("#searchTimeRule").val().trim();
            const operateTime = $dateRangeDisplay.text() === "请选择" ? "" : $dateRangeDisplay.text();

            // 构建导出URL
            let exportUrl = `/NumberingRules/Export?`;
            let params = [];

            if (selectedIds.length > 0) {
                params.push(`selectedIds=${selectedIds.join(",")}`);
            }
            if (targetForm) params.push(`targetForm=${encodeURIComponent(targetForm)}`);
            if (numberPrefix) params.push(`numberPrefix=${encodeURIComponent(numberPrefix)}`);
            if (timeRule) params.push(`timeRule=${encodeURIComponent(timeRule)}`);
            if (operateTime) params.push(`operateTime=${encodeURIComponent(operateTime)}`);

            exportUrl += params.join('&');

            if (selectedIds.length === 0 && params.length === 0) {
                alert('请至少选择一个筛选条件或勾选数据行进行导出');
                return;
            }

            // 创建下载链接
            const link = document.createElement('a');
            link.href = exportUrl;
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            setTimeout(function () {
                const exportCount = selectedIds.length > 0 ? selectedIds.length : '所有筛选';
                alert(`✅ 导出完成！\n\n导出了 ${exportCount} 条数据`);
            }, 500);
        });

        // 11. 删除按钮
        $(document).on("click", ".delete-btn", function (e) {
            e.stopPropagation();
            const ruleId = $(this).data("id");

            if (!confirm("确定要删除这条编号规则吗？删除后不可恢复！")) {
                return;
            }

            const token = $('input[name="__RequestVerificationToken"]').val();

            $.ajax({
                url: "/NumberingRules/Delete",
                type: "POST",
                data: {
                    ruleId: ruleId,
                    __RequestVerificationToken: token
                },
                success: function (res) {
                    if (res.success) {
                        alert("删除成功！");
                        window.refreshRuleTable(); // 删除后刷新表格
                    } else {
                        alert("删除失败：" + res.message);
                    }
                },
                error: function (xhr) {
                    alert("删除失败，错误信息：" + (xhr.responseJSON?.message || "网络错误"));
                }
            });
        });

        // 双日历渲染辅助函数（供重置按钮调用）
        function renderSingleCalendar(type, date, container) {
            container.empty();
            const year = date.getFullYear();
            const month = date.getMonth();
            const firstDay = new Date(year, month, 1);
            const lastDay = new Date(year, month + 1, 0);
            const firstDayOfWeek = firstDay.getDay();
            const prevMonthLastDay = new Date(year, month, 0).getDate();

            // 上月残留日期
            for (let i = 0; i < firstDayOfWeek; i++) {
                const day = prevMonthLastDay - firstDayOfWeek + i + 1;
                const dayEl = $("<div>").addClass("calendar-day other-month").text(day);
                container.append(dayEl);
            }

            // 当月日期
            for (let i = 1; i <= lastDay.getDate(); i++) {
                const dayEl = $("<div>").addClass("calendar-day").text(i);
                container.append(dayEl);
            }

            // 下月补充日期
            const totalDays = firstDayOfWeek + lastDay.getDate();
            const nextMonthNeedDays = 42 - totalDays;
            for (let i = 1; i <= nextMonthNeedDays; i++) {
                const dayEl = $("<div>").addClass("calendar-day other-month").text(i);
                container.append(dayEl);
            }
        }
    });
</script>